// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: linchuan

#include "coin2/exchange/bitstamp/api_order/native_private_client.h"

#include <list>
#include <memory>
#include <string>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/base/order/rate_config.h"
#include "coin2/exchange/bitstamp/symbology/product.h"

constexpr auto EXAMPLE_SPOT_BITSTAMP = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke06/bitstamp/trade_key.json",
  "rate_limit_info": {
    "spot_bitstamp": {
      "req_all": {
        "secs": 600,
        "reqs": 7500
      }
    }
  }
})";

using coin2::exchange::bitstamp::symbology::BitstampProduct;

auto BitstampNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  auto params = RestParams();

  BitstampProduct product =
      BitstampProduct::FromStr(order_spec.product, order_spec.order_created_time);
  params.set_product_id(order_spec.product);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  auto formatter = product_holder->product_info().order_formatter();
  params.set_amount(formatter.FormatQty(order_spec.qty));

  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_type("market");
  } else {
    params.set_type("limit");
    params.set_price(formatter.FormatPrice(order_spec.price));

    if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
      params.set_fok_order("True");
    } else if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
      params.set_ioc_order("True");
    } else {
      params.set_daily_order("True");
    }
  }
  return params;
}

auto BitstampNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  CHECK(order_context.has_exchange_order_id());
  auto params = RestParams();
  params.set_id(order_context.exchange_order_id());
  return params;
}

BitstampNativePrivateClient::BitstampNativePrivateClient(
    const MarketExchangeApi& mea,
    const OrderConnectionConfig& config_override) {
  mea_ = mea;
  OrderConnectionConfig config;
  config.set_rest_host("www.bitstamp.net");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[BitstampNativePrivateClient] config: " << config.DebugString();

  auths_.Construct<BitstampRestAuth, OrderConnectionConfig>(config);

  // rate limit tracker
  using RateConfig = coin2::exchange::base::order::RateConfig;
  coin2::exchange::order::RateLimitInfoSpotBitstamp rate_config;
  RateConfig::Get()->GetConfig(mea_, config, &rate_config);
  if (!rate_config.has_req_all()) {
    RateConfig::CheckFail(mea_.String(), EXAMPLE_SPOT_BITSTAMP);
  }
  const auto& req_all = rate_config.req_all();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\nreq_all: [" << req_all.reqs() << " (reqs) / " << req_all.secs() << " (seconds)]"
            << "\n\nOr you can configure customized rate in driver config. For example: "
            << EXAMPLE_SPOT_BITSTAMP
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
  rate_tracker_ = std::make_unique<RateTracker>(req_all.secs() * 1'000'000'000LL);
  rate_tracker_->SetRateLimitInfo(req_all.reqs(), req_all.reqs());  // linchuan: >8000 will ban IP
  rate_tracker_->SetRateLimitInfoString(&rate_config);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::QueryAccountBalance() {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    DLOG(ERROR) << "Rate limit! QueryAccountBalance not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByPostWithSignature("/api/v2/balance/", &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::QueryOpenOrders() {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    DLOG(ERROR) << "Rate limit! QueryOpenOrders not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByPostWithSignature("/api/v2/open_orders/all/", &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::QueryTrades(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    DLOG(ERROR) << "Rate limit! QueryTrades not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  builder.PutPost("limit", params.limit());
  auto* context =
      GetAuth()->CreateRequestByPostWithSignature("/api/v2/user_transactions/", &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::PlaceOrder(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::PLACE)) {
    DLOG(ERROR) << "Rate limit! PlaceOrder not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  CHECK(params.side() == "buy" || params.side() == "sell");
  std::string type_str = "";
  if (params.type() == "limit") {
    builder.PutPost("price", params.price());
    builder.PutPost("daily_order", params.daily_order());
    builder.PutPost("ioc_order", params.ioc_order());
    builder.PutPost("fok_order", params.fok_order());
  } else {
    type_str = "market/";
  }
  builder.PutPost("amount", params.amount());
  auto* context = GetAuth()->CreateRequestByPostWithSignature(
      "/api/v2/" + params.side() + "/" + type_str + params.product_id() + "/",
      &builder);
  Push(1, ts, ActionType::PLACE);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::CancelOrder(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::CANCEL)) {
    DLOG(ERROR) << "Rate limit! CancelOrder not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  builder.PutPost("id", params.id());
  auto* context = GetAuth()->CreateRequestByPostWithSignature("/api/v2/cancel_order/", &builder);
  Push(1, ts, ActionType::CANCEL);

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> BitstampNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      return QueryAccountBalance();
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      return QueryOpenOrders();
    }
    default: {
      return nullptr;
    }
  }
}
